<template>
  <van-nav-bar title="用户登录" :fixed="true" left-arrow @click-left="$router.back()"/>
  <van-form @submit="onSubmit" class="mt100">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div class="register" @click.stop="router.push('/register')">没有账号？立即注册</div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { login } from '@/api/login'
import { useRouter } from 'vue-router';
import { ref } from 'vue'
import { Toast } from 'vant'

  const router = useRouter()
  const username = ref<string>('');
  const password = ref<string>('');
  const onSubmit = async () => {
    let res = await login(username.value,password.value)
    let err = ''
    if(res.status === 200){
      let token = res.data.access_token
      localStorage.setItem("bookshop-token",token)
      router.push('/')
      Toast.success('登录成功');
    }else if(res.status === 422){
      if(res.data.errors.email){
        err = res.data.errors.email[0]
      }else{
        err = res.data.errors.password[0]
      }
      Toast.fail(err);
    }else if(res.status === 401){
      Toast.fail('用户名或密码错误');
    }
    
  };

</script>

<style scoped lang="less">
.register {
  padding: 32px;
  color: blue;
  font-size: 14px;
}
</style>